import config from '../config';
import { sendReport } from '../export';

const error = () => {
  /**
   * 捕获资源加载失败的错误：js、css、img
   */
  window.addEventListener(
    'error',
    (e) => {
      const target = e.target;
      // 没有target则表示是 js运行错误
      if (!target) return;

      // 捕获资源加载错误
      if (target.src || target.href) {
        const reportData = {
          type: 'error',
          subType: 'resource',
          url: target.src || target.href,
          html: target.outerHTML,
          pageUrl: window.location.href,
          path: e.path,
          startTime: performance.now(),
          config: {
            ...config,
            batchSize: 1,
          },
        };

        // 上报错误
        sendReport(reportData);
      }
    },
    true
  );
  // 捕获js错误
  window.onerror = function (msg, url, lineNo, colNo, error) {
    const reportData = {
      type: 'error',
      subType: 'js',
      msg,
      url,
      colNo,
      lineNo,
      stack: error.stack,
      pageUrl: window.location.href,
      startTime: performance.now(),
      config: {
        ...config,
        batchSize: 1,
      },
    };
    // 上报错误
    sendReport(reportData);
  };

  // 捕获 promise 错误
  window.addEventListener(
    'unhandledrejection',
    (e) => {
      const reportData = {
        type: 'error',
        subType: 'promise',
        reason: e.reason?.stack,
        pageUrl: window.location.href,
        startTime: e.timeStamp,
        config: {
          ...config,
          batchSize: 1,
        },
      };
      // 上报错误
      sendReport(reportData);
    },
    true
  );
};

export default error;
